"""
-*- coding: utf-8 -*-

@author: Du Changping
@time: 2021/12/6 14:53
@file name: gene_fpj
@software：PyCharm

Do not smash your computer!

"""

import time
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


def copy(path_1, path_2):
    """
    将路径path_1下的所有目录及文件复制到路径path_2下
    path_1: 待复制的目录或者文件路径
    path_2: 目标路径
    """
    if os.path.isdir(path_1):  # path_1是目录

        list_1 = os.listdir(path_1)
        if not list_1:  # 复制目录，仅仅是复制空目录
            os.mkdir(path_2)
        else:
            # os.mkdir(path_2)  # 先复制最上层空目录
            for i in list_1:
                path_r = os.path.join(path_1, i)  # 下层目录或文件的绝对路径
                path_w = os.path.join(path_2, i)  # 目标目录或文件的绝对路径
                if os.path.isfile(path_r):  # 是文件则直接进行复制
                    with open(path_r, 'rb') as rstream:
                        container = rstream.read()
                        with open(path_w, 'wb') as wstream:
                            wstream.write(container)
                else:  # 是目录则调用本函数
                    copy(path_r, path_w)

    else:  # path_1是文件
        with open(path_1, 'rb') as rstream:  # 是文件直接复制文件
            container = rstream.read()
            file_name = os.path.basename(path_1)
            path_2 = os.path.join(path_2, file_name)
            with open(path_2, 'wb') as wstream:
                wstream.write(container)
            wstream.close()
        rstream.close()


if __name__ == "__main__":
    timestamp = time.strftime("%m%d-%H%M%S", time.localtime())

    # basic setting
    whole_projection_dir = "fpj" + timestamp
    if not os.path.exists(whole_projection_dir):
        os.mkdir(whole_projection_dir)

    # file path setting todo
    input_dir_path = r"G:\CT_reco\week\homework1204\rec2\img"
    input_file_name = "img_test.raw"
    # input_file_name = "img_*.raw"

    output_dir_name = r"sgm-"+timestamp
    output_dir_path = whole_projection_dir + r"/{}".format(output_dir_name)

    # image dimension setting todo
    ImageDimension = 512
    PixelSize = 0.4

    # projection setting todo
    SourceIsocenterDistance = 1000000  # sod
    SourceDetectorDistance = 1000000  # sdd
    DetectorElementCount = 400  # sinogram width
    Views = 360  # sinogram height
    DetectorElementSize = 0.5  # add physical background

    # basic test
    original_img_file = os.listdir(input_dir_path)
    print(original_img_file)
    test_img_path = os.path.join(input_dir_path, original_img_file[0])
    test_img = np.fromfile(test_img_path, dtype=np.float32)
    assert test_img.shape[0] == ImageDimension ** 2, \
        " please check the image dimension, here test img's dimension is{}," \
        " while the set dimension is {}, " \
        "its square is {}".format(test_img.shape[0],
                                  ImageDimension,
                                  ImageDimension ** 2)

    if not os.path.exists(output_dir_path):
        os.mkdir(output_dir_path)

    to_save_img_dir = whole_projection_dir + r"/img" + timestamp
    print(to_save_img_dir)
    if not os.path.exists(to_save_img_dir):
        os.mkdir(to_save_img_dir)
    copy(input_dir_path, to_save_img_dir)

    josnc_path = os.path.join(whole_projection_dir, "fpj.jsonc")
    f_ = open(josnc_path, "w")

    f_.write("// This is a config sample for mgfpj\n\n{")
    f_.write("  /*********************************************************\n")
    f_.write("  * input and output directory and files\n")
    f_.write("  *********************************************************/\n")
    f_.write("  \"InputDir\": \"./{}\",\n".format(r"img" + timestamp))
    f_.write("  \"OutputDir\": \"./{}\",\n".format(output_dir_name))
    f_.write("  // all the files in the input directory, use regular expression\n")
    f_.write("  \"InputFiles\": \"{}\",\n".format(input_file_name))  # todo
    f_.write("  // output file name (prefix, replace)\n")
    f_.write("  \"OutputFilePrefix\": \"{}\",\n".format(""))
    f_.write("  // replace substring in input file name\n")
    f_.write("  \"OutputFileReplace\": [ \"img_\", \"sgm_\" ],\n")
    f_.write("\n")
    f_.write("  /*********************************************************\n")
    f_.write("	 * image parameters\n")
    f_.write("	 *********************************************************/\n")
    f_.write("   // image dimension (integer)\n")
    f_.write("  \"ImageDimension\": {},\n".format(ImageDimension))
    f_.write("  /* pixel size or image size, just use one of them */\n")
    f_.write("  // image pixel size [mm]\n")
    f_.write("  \"PixelSize\": {},\n".format(PixelSize))
    f_.write("\n\n")
    f_.write("  /*********************************************************\n")
    f_.write("    * geometry and detector parameters\n")
    f_.write("    *********************************************************/\n")
    f_.write("  // source to isocenter distance [mm]\n")
    f_.write("  \"SourceIsocenterDistance\": {},\n".format(SourceIsocenterDistance))
    f_.write("  // source to detector distance [mm]\n")
    f_.write("  \"SourceDetectorDistance\": {},\n".format(SourceDetectorDistance))
    f_.write("  // number of detector elements\n")
    f_.write("  \"DetectorElementCount\": {},\n".format(DetectorElementCount))
    f_.write("  // number of views for reconstruction\n")
    f_.write("  \"Views\": {},\n".format(Views))
    f_.write("  // the physical size of detector element size [mm]\n")
    f_.write("  \"DetectorElementSize\": {},\n".format(DetectorElementSize))
    f_.write("\n\n\n\n")
    f_.write("  /*********************************************************\n")
    f_.write("    * parameters by default\n")
    f_.write("    *********************************************************/\n")
    f_.write("  // number of slices in each image file\n")
    f_.write("  \"SliceCount\": {},\n".format(1))
    f_.write("  // start angle (positive counterclockwise) [degree]\n")
    f_.write("  \"StartAngle\": {}\n,".format(0))
    f_.write("  // oversample sinogram by increasing the number of detector elements by the factor of number below\n")
    f_.write("  \"OversampleSize\": {},\n".format(2))
    f_.write("  // the position (coordinate) of detector center [mm]\n")
    f_.write("  \"DetectorOffcenter\": {},\n".format(0))
    f_.write("  // (OPTIONAL) Whether the cone beam recon is needed\n")
    f_.write("  // in case of \"false\", all other items related to cone beam recon will be null\n")
    f_.write("  \"ConeBeam\": {}\n".format("false"))
    f_.write("}")
    f_.write("\n")
    f_.close()
